package com.newenergy.wisehome.ui.fragment;

import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.stuxuhai.jpinyin.PinyinException;
import com.github.stuxuhai.jpinyin.PinyinFormat;
import com.github.stuxuhai.jpinyin.PinyinHelper;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.newenergy.wisehome.R;
import com.newenergy.wisehome.common.util.LocaleUtil;
import com.newenergy.wisehome.config.AppManager;
import com.newenergy.wisehome.data.bean.DeviceCategory;
import com.newenergy.wisehome.data.bean.Family;
import com.newenergy.wisehome.data.ormlite.dao.DeviceCategoryDao;
import com.newenergy.wisehome.ui.adapter.HEAAdapter;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;
import me.yokeyword.fragmentation.ISupportFragment;

/**
 * Created by kyx on 2018/7/9.
 * 小家电管理界面
 */

public class HEAFragment extends BaseFragment {

    private static String ARG_EQUIPMENT = "arg_equipment";
    @BindView(R.id.btn_back)
    Button mBtnBack;
    @BindView(R.id.tv_back)
    TextView mTvBack;
    @BindView(R.id.tv_page)
    TextView mTvPage;
    @BindView(R.id.recyclerView)
    EasyRecyclerView mRecyclerView;
    @BindView(R.id.btn_add_equip)
    Button mBtnAddEquip;
    @BindView(R.id.tv_empty)
    TextView mTvEmpty;
    @BindView(R.id.rl_empty)
    RelativeLayout mRlEmpty;

    private Family mFamily;
    private HEAAdapter mAdapter;
    private LinearLayoutManager mLayoutManager;
    private int mGroupPosition = 0;
    private DeviceCategory mGroup;
    private Dialog mEditDialog;
    private EasyRecyclerView mIconRecyclerView;
    private PopupWindow mPopupWindow;
    private int confirmType = 1;
    private TextView mTv_tip;

    public static ISupportFragment newInstace(Family currFamily) {
        Bundle args = new Bundle();
        args.putParcelable(ARG_EQUIPMENT, currFamily);
        HEAFragment fragment = new HEAFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public int getLayoutId() {
        return R.layout.fragment_equipment;
    }


    @Override
    public void init(View rootView) {
        initRecycleView();
        mFamily = getArguments().getParcelable(ARG_EQUIPMENT);
        mTvPage.setText(mFamily.getName());
        if (mFamily.getType() != 0) {
            mBtnAddEquip.setVisibility(View.VISIBLE);
        } else {
            mBtnAddEquip.setVisibility(View.INVISIBLE);
        }


        DeviceCategoryDao deviceCategoryDao = new DeviceCategoryDao(getContext());
        List<DeviceCategory> groups = new ArrayList<>();
        DeviceCategory defaultDeviceCategoryFanlamp = AppManager.getInstance(getContext()).mDefaultDeviceCategoryFanLamp;
        DeviceCategory defaultDeviceCategoryDataFanlamp = AppManager.getInstance(getContext()).mDefaultDeviceCategoryDataFanLamp;
        DeviceCategory defaultDeviceCategoryFan = AppManager.getInstance(getContext()).mDefaultDeviceCategoryFan;
        DeviceCategory defaultDeviceCategoryHumidifier = AppManager.getInstance(getContext()).mDefaultDeviceCategoryHumidifier;
        DeviceCategory defaultDeviceCategoryBathHeater = AppManager.getInstance(getContext()).mDefaultDeviceCategoryBathHeater;
        groups.add(defaultDeviceCategoryFanlamp);
        groups.add(defaultDeviceCategoryDataFanlamp);
        groups.add(defaultDeviceCategoryFan);
        groups.add(defaultDeviceCategoryHumidifier);
        groups.add(defaultDeviceCategoryBathHeater);
        groups.addAll(deviceCategoryDao.getFamilyHEA(mFamily.getFamilyId()));

        mAdapter.refreshData(groups);
        setCurrItem();
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            DeviceCategoryDao deviceCategoryDao = new DeviceCategoryDao(getContext());
            List<DeviceCategory> groups = new ArrayList<>();
            DeviceCategory defaultDeviceCategoryFanlamp = AppManager.getInstance(getContext()).mDefaultDeviceCategoryFanLamp;
            DeviceCategory defaultDeviceCategoryDataFanlamp = AppManager.getInstance(getContext()).mDefaultDeviceCategoryDataFanLamp;
            DeviceCategory defaultDeviceCategoryFan = AppManager.getInstance(getContext()).mDefaultDeviceCategoryFan;
            DeviceCategory defaultDeviceCategoryHumidifier = AppManager.getInstance(getContext()).mDefaultDeviceCategoryHumidifier;
            DeviceCategory defaultDeviceCategoryBathHeater = AppManager.getInstance(getContext()).mDefaultDeviceCategoryBathHeater;
            groups.add(defaultDeviceCategoryFanlamp);
            groups.add(defaultDeviceCategoryDataFanlamp);
            groups.add(defaultDeviceCategoryFan);
            groups.add(defaultDeviceCategoryHumidifier);
            groups.add(defaultDeviceCategoryBathHeater);
            groups.addAll(deviceCategoryDao.getFamilyHEA(mFamily.getFamilyId()));

            mAdapter.refreshData(groups);
            setCurrItem();
        }
    }

    private void initRecycleView() {
        Context context = getContext();
        mAdapter = new HEAAdapter(context);
        mRecyclerView.setAdapter(mAdapter);
        mLayoutManager = new LinearLayoutManager(context);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mAdapter.setOnItemClickListener(position -> {
            mGroupPosition = position;
            setCurrItem();
        });

        mAdapter.setItemEditCallBack(new HEAAdapter.ItemEditCallBack() {
            @Override
            public void notifyPage(int position) {
                mGroupPosition = position;
                mGroup = mAdapter.getItem(mGroupPosition);
                setCurrItem();
                showEditDialog();
            }
        });

    }


    private void setCurrItem() {
        List<DeviceCategory> deviceCategoryList = mAdapter.getAllData();
        if (deviceCategoryList == null || deviceCategoryList.size() < 1) {
            mGroupPosition = 0;
            mGroup = null;
            AppManager.getInstance(getContext()).selectGroup = null;
            mRlEmpty.setVisibility(View.VISIBLE);
            mRecyclerView.setVisibility(View.GONE);
            mTvEmpty.setText(R.string.add_hea_first);//"当前家庭还没有添加小家电设备！"
            return;
        }
        for (DeviceCategory group : deviceCategoryList) {
            group.setChecked(false);
        }

        mRecyclerView.setVisibility(View.VISIBLE);
        mRlEmpty.setVisibility(View.GONE);
        mGroup = deviceCategoryList.get(mGroupPosition);
        mGroup.setChecked(true);
        mAdapter.notifyDataSetChanged();
    }


    private void showEditDialog() {
        mEditDialog = new Dialog(getContext(), R.style.CustomDialog);
        View contentView = View.inflate(getContext(), R.layout
                .dialog_edit_group, null);
        mEditDialog.setContentView(contentView);
        EditText et_name = (EditText) contentView.findViewById(R.id
                .et_name);
        Button btn_delete = (Button) contentView.findViewById(R.id
                .btn_delete);
        Button btn_select_icon = (Button) contentView.findViewById
                (R.id.btn_select_icon);
        Button btn_confirm = (Button) contentView.findViewById(R.id
                .btn_confirm);
        Button btn_cancel = (Button) contentView.findViewById(R.id
                .btn_cancel);

        mTv_tip = (TextView) contentView.findViewById(R.id
                .tv_tip);

        btn_select_icon.setVisibility(View.GONE);
        String groupName = mGroup.getName();
        et_name.setText(groupName);
        et_name.setSelection(groupName.length());

        mEditDialog.show();
        btn_delete.setOnClickListener(v -> {
            mEditDialog.dismiss();
            confirmType = 1;
            String msg = getString(R.string.sure_delete) + mGroup.getName() + "?";
            showConfirmDialog(msg);

        });
        btn_select_icon.setOnClickListener(v -> {
            showPopupWindow(et_name);
        });
        btn_confirm.setOnClickListener(v -> {
            String name = et_name.getText().toString().trim();
            updateGroupName(name);
            DeviceCategoryDao deviceCategoryDao = new DeviceCategoryDao(getContext());
            deviceCategoryDao.updateDeviceCategory(mGroup);

            setCurrItem();

        });
        btn_cancel.setOnClickListener(v -> {
            mEditDialog.dismiss();
        });
    }


    private void updateGroupName(String name) {
        String oldName = mGroup.getName();
        if (oldName.equals(name)) {
            mEditDialog.dismiss();
            mEditDialog = null;
            return;
        }

        if (isHaveNum(name)) {
//            toast(getString(R.string.naming_no_contain_num));
            mTv_tip.setText(getString(R.string.naming_no_contain_num));
            return;
        }

        /*boolean isOk = checkGroupName(name);
        if (!isOk) return;*/
        DeviceCategoryDao deviceCategoryDao = new DeviceCategoryDao(getContext());
        if (TextUtils.isEmpty(name)) {
//            myToast(getString(R.string.tip_room_name_nonull), true);
            mTv_tip.setText(getString(R.string.tip_room_name_nonull));
            return;
        }

        if (LocaleUtil.getLanguage().startsWith("zh")) {
            if (name.length() < 2 || name.length() > 10) {
//                ToastUtil.myToast(getString(R.string.tip_room_name_range), true);
                mTv_tip.setText(getString(R.string.tip_room_name_range));
                return;
            }

        } else {
            if (name.length() < 1) {
//                ToastUtil.myToast(getString(R.string.tip_room_name_range), true);
                mTv_tip.setText(getString(R.string.tip_room_name_range));
                return;
            }
        }


        if (name.contains("[") || name.contains("#") || name
                .contains("&")) {
//            ToastUtil.myToast(getString(R.string.tip_room_name_error), true);
            mTv_tip.setText(getString(R.string.tip_room_name_error));
            return;
        }

        if (mCurrFamily == null) return;
        DeviceCategory group = deviceCategoryDao.getDeviceCategoryByName(mCurrFamily.getFamilyId(), name);
        if (group != null) {
//            myToast(getString(R.string.tip_room_name_used), true);
            mTv_tip.setText(getString(R.string.tip_room_name_used));
            return;
        }


        mGroup.setName(name);
        try {
            String pinyinString = PinyinHelper.convertToPinyinString(name, " ", PinyinFormat.WITHOUT_TONE);
            mGroup.setPingyinName(pinyinString);

        } catch (PinyinException e) {
            e.printStackTrace();
        }

        mEditDialog.dismiss();
        mEditDialog = null;
    }


    public void showPopupWindow(View dropView) {
        mPopupWindow = new PopupWindow(mIconRecyclerView, dpToPx(200), dpToPx(150));
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopupWindow.setOutsideTouchable(false);
        mPopupWindow.setFocusable(true);
        mPopupWindow.showAsDropDown(dropView, -dpToPx(20), dpToPx(3));
    }


    @OnClick({R.id.btn_back, R.id.tv_back, R.id.btn_add_equip})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                doBack();

                break;
            case R.id.tv_back:
                doBack();

                break;
            case R.id.btn_add_equip:
                start(ScanHEAFramgment.newInstance(mFamily));

                break;
        }
    }

    @Override
    protected void confirmOperation() {
        super.confirmOperation();
        if (confirmType == 1) {
            deleteGroup();
        }
    }


    private void deleteGroup() {
        DeviceCategoryDao deviceCategoryDao = new DeviceCategoryDao(getContext());
        deviceCategoryDao.delete(mGroup);
        mAdapter.remove(mGroup);
        mGroupPosition = 0;
//        myToast(getString(R.string.delete) + mGroup.getName() + getString(R.string.success), false);
        setCurrItem();
    }


    public boolean isHaveNum(String str) {
        Pattern pattern = Pattern.compile("[0-9]");
        Matcher isNum = pattern.matcher(str);
        if (isNum.find()) {
            return true;
        }
        return false;
    }


}
